﻿// -----------------------------------------------------------------------
//  <copyright file="CorrelationIdMiddleware.cs" company="LiuliuSoft">
//      Copyright (c) 2025 66SOFT. All rights reserved.
//  </copyright>
//  <site>https://ifs.66soft.net</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-10-15 14:10</last-date>
// -----------------------------------------------------------------------

using Microsoft.AspNetCore.Http;

using Serilog.Context;


namespace Shares.Infrastructure.Logging;

public class CorrelationIdMiddleware(RequestDelegate next)
{
    public async Task Invoke(HttpContext context)
    {
        var correlationId = context.Request.Headers["X-Correlation-ID"].FirstOrDefault()
            ?? Guid.NewGuid().ToString();

        // 将关联 ID 注入日志上下文
        using (LogContext.PushProperty("CorrelationId", correlationId))
        {
            context.Response.Headers.Append("X-Correlation-ID", correlationId);
            await next(context);
        }
    }
}